import SpatialReference from "@arcgis/core/geometry/SpatialReference";
import BaseDynamicLayer from "@arcgis/core/layers/BaseDynamicLayer";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer";
import TileInfo from "@arcgis/core/layers/support/TileInfo";
import { mapServiceIp, mapGeoserverIp, MapOptions } from "api/config";

// 边界
export const bbox = [
  528134.2439974264, 2479133.132957764, 848266.928417676, 2634523.9978181086,
];

// 自定义坐标系
export const spatialReference = new SpatialReference({
  wkt: 'PROJCS["CGCS2000 3 Degree GK CM 113E",GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",700000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",113.0],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]',
});

// 自定义坐标系范围
export const baseLods = [
  { level: 0, resolution: 156543.34701231902, scale: 5.916587109e8 },
  { level: 1, resolution: 78271.67350615951, scale: 2.9582935545e8 },
  { level: 2, resolution: 39135.83675440268, scale: 1.4791467773e8 },
  { level: 3, resolution: 19567.91837587842, scale: 7.395733886e7 },
  { level: 4, resolution: 9783.95918793921, scale: 3.697866943e7 },
  { level: 5, resolution: 4891.979595292524, scale: 1.848933472e7 },
  { level: 6, resolution: 2445.989797646262, scale: 9244667.36 },
  { level: 7, resolution: 1222.994898823131, scale: 4622333.68 },
  { level: 8, resolution: 611.4974494115655, scale: 2311166.84 },
  { level: 9, resolution: 305.74872470578276, scale: 1155583.42 },
  { level: 10, resolution: 152.87436235289138, scale: 577791.71 },
  { level: 11, resolution: 76.43717985352637, scale: 288895.85 },
  { level: 12, resolution: 38.2185912496825, scale: 144447.93 },
  { level: 13, resolution: 19.10929430192194, scale: 72223.96 },
  { level: 14, resolution: 9.55464715096097, scale: 36111.98 },
  { level: 15, resolution: 4.777323575480485, scale: 18055.99 },
  { level: 16, resolution: 2.3886631106595546, scale: 9028 },
  { level: 17, resolution: 1.1943315553297773, scale: 4514 },
  { level: 18, resolution: 0.5971657776648887, scale: 2257 },
  { level: 19, resolution: 0.2985828888324443, scale: 1128.5 },
  { level: 20, resolution: 0.14929144441622216, scale: 564.25 },
  { level: 21, resolution: 0.07464572220811108, scale: 282.125 },
];

// 自定义坐标系的瓦片信息
export const tileInfo = new TileInfo({
  dpi: 96,
  rows: 256,
  cols: 256,
  compressionQuality: 0,
  origin: {
    x: -4923200.0,
    y: 10002100,
  },
  lods: baseLods,
  spatialReference,
});

// 自定义坐标系的fullExtend
export const fullExtent = {
  xmin: bbox[0],
  ymin: bbox[1],
  xmax: bbox[2],
  ymax: bbox[3],
  spatialReference,
};

// 创建图片
// 获取wms服务的参数
export const getWmsParams = ({ name, params }) => {
  const layers = name.split(":")[1];
  return {
    service: "WMS",
    version: "1.1.0",
    request: "GetMap",
    srs: "EPSG:44901",
    layers,
    bbox: bbox.join(","),
    format: "image/png",
    ...params,
  };
};

// 获取wfs服务的参数
export const getWfsParams = ({ name, params }) => {
  const typeName = name.split(":")[1];
  return {
    service: "WFS",
    version: "1.0.0",
    request: "GetFeature",
    srs: "EPSG:44901",
    typeName,
    outputFormat: "gml2",
    ...params,
  };
};

// 获取图片图层地图服务基础url
export const getImageBaseConfig = ({ name, type, params }) => {
  const serviceName = name.split(':')[0];
  
  const url = `${mapGeoserverIp}/${MapOptions()}/geoserver/${serviceName}/${type}`;
  const serviceParams =
    type === "wms"
      ? getWmsParams({ name, params })
      : getWfsParams({ name, params });

  return {
    url,
    params: serviceParams,
  };
};

// 创建图片图层
export const createGeoserverImageLayer = ({ name, params, title, visible = true }) => {
  const config = getImageBaseConfig({ name, type: "wms", params });

  const Func = BaseDynamicLayer.createSubclass({
    getImageUrl: function (extent, width, height) {
      const { xmin, xmax, ymin, ymax } = extent;
      const urlParams = {
        width,
        height,
        size: `${width},${height}`,
        transparent: true,
        ...config.params,
        bbox: `${xmin},${ymin},${xmax},${ymax}`,
      };

      let paramsText = "";
      Object.keys(urlParams).forEach(
        (key) => (paramsText += `&${key}=${urlParams[key]}`)
      );
      paramsText.replace("&", "");

      return `${config.url}?${paramsText}`;
    },
  });

  const layer = new Func();

  layer.title = title;

  layer.visible = visible;

  return layer;
};
// 创建图片

// 创建瓦片
// 获取地图服务基础url
export const getMapServiceBaseUrl = ({ type, name }) => {
  return `${mapServiceIp}/ServiceAccess/${type}/${name}/e33eaedd447f640d0458cb236c3dae4d`;
}

// 创建瓦片/图片图层
export const createMapServiceWebTileLayer = ({
  type,
  name,
  title,
  template = "/tile/{level}/{row}/{col}?blankTile=false",
  visible = true
}) => {
  const url = getMapServiceBaseUrl({ type, name });

  return new WebTileLayer({
    title: title || name,
    urlTemplate: `${url}${template}`,
    spatialReference,
    fullExtent,
    tileInfo,
    opacity: 1,
    visible,
  });
};
// 创建瓦片
